package com.wanxiang.commonlib.utils;

import android.text.TextUtils;
import android.util.Log;

import com.wanxiang.commonlib.configs.DebugConfigs;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.RandomAccessFile;
import java.util.Calendar;
import java.util.Locale;


public class LogUtils {

    private static String TAG = "Launcher";
    //public static final boolean mIsDebug = false;
    private final static String mLogFilePath = "/sdcard/TuYa_First.txt";
    private final static String mLogTwoFilePath = "/sdcard/TuYa_Second.txt";
    private final static int mLogFileMaxLength = 30 * 1024 * 1024;

    public static void d(String format, Object... args) {
        if (!DebugConfigs.isDebug) return;
        if ((DebugConfigs.isDebug || DebugConfigs.isSingnDubug) && args != null) {
            LogUtils.Logd(TAG, buildMessage(format, args));
        }
    }


    public static void d_tag(String tag, String format, Object... args) {
        if (!DebugConfigs.isDebug) return;
        if ((DebugConfigs.isDebug || DebugConfigs.isSingnDubug) && args != null) {
            LogUtils.Logd(TAG, buildMessage(format, args));
        }
    }

    public static void e(String format, Object... args) {
        if (!DebugConfigs.isDebug) return;
        if ((DebugConfigs.isDebug || DebugConfigs.isSingnDubug) && args != null) {
            LogUtils.Logd(TAG, buildMessage(format, args));
        }
    }

    public static void e(String tag, String format, Object... args) {
        if (!DebugConfigs.isDebug) return;
        if ((DebugConfigs.isDebug || DebugConfigs.isSingnDubug) && args != null) {
            LogUtils.Logd(tag, buildMessage(format, args));
        }
    }

    /**
     * Formats the caller's provided message and prepends useful info like
     * calling thread ID and method name.
     */
    private static String buildMessage(String format, Object... args) {
        String msg = format;
        try {
            msg = (args == null) ? format : String.format(Locale.US, format, args);
        } catch (Exception e) {
            msg = format;
        }

        StackTraceElement[] trace = new Throwable().fillInStackTrace().getStackTrace();

        String caller = "<unknown>";
        // Walk up the stack looking for the first caller outside of VolleyLog.
        // It will be at least two frames up, so start there.
        for (int i = 2; i < trace.length; i++) {
            Class<?> clazz = trace[i].getClass();
            if (!clazz.equals(LogUtils.class)) {
                String callingClass = trace[i].getClassName();
                callingClass = callingClass.substring(callingClass.lastIndexOf('.') + 1);
                callingClass = callingClass.substring(callingClass.lastIndexOf('$') + 1);

                caller = callingClass + "." + trace[i].getMethodName() + " line:" + trace[i].getLineNumber();
                break;
            }
        }
        return String.format(Locale.US, "[%d] %s-----> %s", Thread.currentThread().getId(), caller, msg);
    }


    public static void write(String msg) {
        if (!DebugConfigs.isDebug) return;
        if (TextUtils.isEmpty(msg)) return;
        Logd(TAG, msg);
    }

    public static void Logd(String tag, String msg) {
        /* if(!DebugConfigs.isDebug) return;*/
        //LogUtils.Logd(TAG, msg);
        Log.d(tag, msg);
    }
    public static void Loge(String tag, String msg) {
        if (tag == null || tag.length() == 0
                || msg == null || msg.length() == 0)
            return;

        int segmentSize = 3 * 1024;
        long length = msg.length();
        if (length <= segmentSize ) {// 长度小于等于限制直接打印
            Log.e(tag, msg);
        }else {
            while (msg.length() > segmentSize ) {// 循环分段打印日志
                String logContent = msg.substring(0, segmentSize );
                msg = msg.replace(logContent, "");
                Log.e(tag, logContent);
            }
            Log.e(tag, msg);// 打印剩余日志
        }
    }
    public synchronized static void writeLogToFile(String msg) {
        if (!DebugConfigs.isDebug) return;
        try {
            File fileOne = new File(mLogFilePath);
            if (!fileOne.exists()) fileOne.createNewFile();
            File file = fileOne;
            if (fileOne.length() > mLogFileMaxLength) {
                File fileTwo = new File(mLogTwoFilePath);
                if (!fileTwo.exists()) fileTwo.createNewFile();
                if (fileTwo.length() > mLogFileMaxLength) {
                    fileOne.delete();
                    fileOne.createNewFile();
                    fileTwo = null;
                    file = fileOne;
                } else {
                    fileOne = null;
                    file = fileTwo;
                }
            } else {
                file = fileOne;
            }
            RandomAccessFile randomAccessFile = new RandomAccessFile(file, "rw");
            randomAccessFile.seek(randomAccessFile.length());
            BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(randomAccessFile.getFD()));
            bufferedWriter.write(Calendar.getInstance(Locale.CHINA).getTime().toLocaleString() + " : " + msg);
            bufferedWriter.newLine();
            try {
                bufferedWriter.flush();
                bufferedWriter.close();
                bufferedWriter = null;
            } catch (Exception e) {
                e.printStackTrace();
            }
            try {
                randomAccessFile.close();
                randomAccessFile = null;
            } catch (Exception e) {
                e.printStackTrace();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public static void logd(String info) {
        logd("---===chain", info);
    }

    public static void logd(String tag, String info) {
        if (info != null) {
            StackTraceElement stack[] = (new Throwable()).getStackTrace();
            if (stack.length > 1) {
                StackTraceElement s = stack[1];
                String[] names = s.getClassName().split("\\.");
                LogUtils.Logd(tag, "[" + names[names.length - 1] + "  " + s.getLineNumber() + "]-->> " + info);
            } else {
                LogUtils.Logd(tag, info);
            }
        }
    }

    public static void loge(String tag, String info) {
        if (info != null) {
            StackTraceElement stack[] = (new Throwable()).getStackTrace();
            if (stack.length > 1) {
                StackTraceElement s = stack[1];
                String[] names = s.getClassName().split("\\.");
                LogUtils.Logd(tag, "[" + names[names.length - 1] + "  " + s.getLineNumber() + "]-->> " + info);
            } else {
                LogUtils.Logd(tag, info);
            }
        }
    }


    public static void LogOutDetail(String tag, String info) {
        if ((DebugConfigs.isDebug || DebugConfigs.isSingnDubug) && info != null) {
            StackTraceElement stack[] = (new Throwable()).getStackTrace();
            if (stack.length > 3) {
                StringBuffer buffer = new StringBuffer();
                buffer.append(info);
                buffer.append("<--");
                String[] names = stack[1].getClassName().split("\\.");
                buffer.append(names[names.length - 1] + "第" + stack[1].getLineNumber() + "行<--");
                names = stack[2].getClassName().split("\\.");
                buffer.append(names[names.length - 1] + "第" + stack[2].getLineNumber() + "行<--");
                names = stack[3].getClassName().split("\\.");
                buffer.append(names[names.length - 1] + "第" + stack[3].getLineNumber() + "行");
                LogUtils.Logd(TAG, buffer.toString());
            } else {
                LogUtils.Logd(TAG, info);
            }
        }
    }


}
